package com.fengwk.support.code;

import java.io.Serializable;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA非对称加密
 * 
 * @author Administrator
 *
 */
public class RSA implements Serializable {
	
	private static final long serialVersionUID = -384630391721542687L;
	
	static final String ALGORITHM_RSA = "RSA";
	
	/**
	 * 公钥
	 */
	private RSAKey publicKey;
	
	/**
	 * 私钥
	 */
	private RSAKey privateKey;
	
	/**
	 * 通过秘钥长度构建新的RSA算法
	 * 
	 * @param keySize 秘钥bit长度>=512
	 * @throws NoSuchAlgorithmException 
	 */
	public RSA(int keySize) throws NoSuchAlgorithmException {
		//为RSA算法创建一个KeyPairGenerator对象
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(ALGORITHM_RSA);
        //初始化KeyPairGenerator对象,密钥长度
        kpg.initialize(keySize);
        //生成密匙对
        KeyPair keyPair = kpg.generateKeyPair();
        
        publicKey = new RSAKey(keyPair.getPublic());
        privateKey = new RSAKey(keyPair.getPrivate());
	}
	
	/**
	 * 通过公钥和私钥构建新的RSA算法
	 * 
	 * @param publicKey
	 * @param privateKey
	 * @throws NoSuchAlgorithmException 
	 * @throws InvalidKeySpecException 
	 */
	public RSA(byte[] publicKeyData, byte[] privateKeyData) throws NoSuchAlgorithmException, InvalidKeySpecException {
		KeyFactory keyFactory = KeyFactory.getInstance(RSA.ALGORITHM_RSA);
		// 从字节流转为公钥对象
		if (publicKeyData != null) {
			X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKeyData);
			publicKey = new RSAKey(keyFactory.generatePublic(x509KeySpec));
		}
		// 从字节流转为私钥对象
        if (privateKeyData != null) {
    		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyData);
    		privateKey = new RSAKey(keyFactory.generatePrivate(pkcs8KeySpec));
        }
	}

	public RSAKey getPublicKey() {
		return publicKey;
	}

	public RSAKey getPrivateKey() {
		return privateKey;
	}
	
}
